﻿//// Reference http://csharp.net-informations.com/communications/csharp-socket-programming.htm
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace SockServer
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress[] address = Dns.GetHostAddresses("LocalHost");
            TcpListener serverSocket = new TcpListener(address[1], 8888);
            int requestCount = 0;
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine("Server started...");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine("Accept connection from client...");
            NetworkStream networkStream = clientSocket.GetStream();
            FileStream fs = new FileStream("test.txt", FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);

            while (true)
            {
                try
                {
                    requestCount++;
                    int bufferSize = clientSocket.ReceiveBufferSize;
                    byte[] byteStream = new byte[bufferSize];
                    networkStream.Read(byteStream, 0, clientSocket.ReceiveBufferSize);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(byteStream);
                    sw.WriteLine(dataFromClient.Trim());
                    Console.WriteLine("Client data send request {0}", requestCount);
                    string serverResponse = "Server response " + Convert.ToString(requestCount);
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine("..." + serverResponse);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }
            }

            sw.Flush();
            sw.Close();
            fs.Close();
            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine("Press Enter<> to exit the server");
            Console.Read();
        }
    }
}
